#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "los_task.h"
#include "los_mux.h"
#include "ohos_init.h"

/* 互斥锁 */
UINT32 g_testMux;
/* 任务ID */
UINT32 g_testTaskId01;
UINT32 g_testTaskId02;
/**
 * @brief 任务1
 * 
 */
void Example_MutexTask1(void)
{
    UINT32 ret;
    printf("task1 timeout and try to get mutex, wait forever.\n");
    while(1){
       
        /* 申请互斥锁 */
        ret = LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER);
        if (ret == LOS_OK) {
            printf("task1 get mutex g_testMux and suspend 5s.\n");
            /* 任务休眠5s */
            LOS_Msleep(5000); 
            /* 释放互斥锁 */
            LOS_MuxPost(g_testMux);
            printf("task1 resumed and post the g_testMux\n");
        }
        else
        {
            printf("task1 get mutex g_testMux fail %d.\n",ret);
        }
    }
    return;
}
/**
 * @brief 任务2
 * 
 */
void Example_MutexTask2(void)
{
    UINT32 ret;
    printf("task2 try to get mutex, wait forever.\n");
    while(1){
        
        /* 申请互斥锁 */
        ret = LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER);
        if (ret == LOS_OK) {
            printf("task2 get mutex g_testMux and suspend 5s.\n");
            /* 任务休眠5s */
            LOS_Msleep(5000); 
            /* 释放互斥锁 */
            LOS_MuxPost(g_testMux);
            printf("task2 resumed and post the g_testMux\n");
        }
        else
        {
            printf("task2 get mutex g_testMux fail %d.\n",ret);
        }
    }
    
    return;
}

UINT32 Mutex_example(void)
{
    UINT32 ret;
    TSK_INIT_PARAM_S task1;
    TSK_INIT_PARAM_S task2;
    /* 初始化互斥锁 */
    LOS_MuxCreate(&g_testMux);
    /* 锁任务调度 */
    LOS_TaskLock();
    /* 创建任务1 */
    memset(&task1, 0, sizeof(TSK_INIT_PARAM_S));
    task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask1;
    task1.pcName       = "MutexTsk1";
    task1.uwStackSize  = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
    task1.usTaskPrio   = 25;
    ret = LOS_TaskCreate(&g_testTaskId01, &task1);
    if (ret != LOS_OK) {
        printf("task1 create failed.\n");
        return LOS_NOK;
    }
    /* 创建任务2 */
    memset(&task2, 0, sizeof(TSK_INIT_PARAM_S));
    task2.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask2;
    task2.pcName       = "MutexTsk2";
    task2.uwStackSize  = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
    task2.usTaskPrio   = 24;
    ret = LOS_TaskCreate(&g_testTaskId02, &task2);
    if (ret != LOS_OK) {
        printf("task2 create failed.\n");
        return LOS_NOK;
    }
    /* 解锁任务调度 */
    LOS_TaskUnlock();
    
    return LOS_OK;
}


